package com.atguigu.statemachine.service;

import com.atguigu.statemachine.config.OrderEvents;
import com.atguigu.statemachine.config.OrderStatus;
import com.atguigu.statemachine.entity.Order;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;

/**
 * @author Jungle
 * @create 2025-05-22 9:00
 * @description
 */
@Service
@Slf4j
public class OrderProcessor {
    @Resource
    private StateMachine<OrderStatus, OrderEvents> orderStateMachine;


    @Resource
    private StateMachinePersister<OrderStatus, OrderEvents, Order> persister;

    public Boolean process(Order order, OrderEvents events) {
        Message<OrderEvents> message = MessageBuilder.withPayload(events)
                .setHeader("order", order).build();
        return sendEvent(message);

    }

    @SneakyThrows
    public Boolean sendEvent(Message<OrderEvents> message) {
        Order order = (Order) message.getHeaders().get("order");
        persister.restore(orderStateMachine,order);
        return orderStateMachine.sendEvent(message);
    }
}
